const crypto = require("crypto");
//hook ip白名单
const whiteListIps = ["::ffff:10.1.1.20","::ffff:10.1.1.25"];

/**
 * 验证身份 github
 */
function checkAuthGithub(req) {
  //github的验证方式
  const signature = `sha1=${crypto
    .createHmac("sha1", appToken)
    .update(JSON.stringify(req.body))
    .digest("hex")}`;
  return signature == req.headers["x-hub-signature"];
}

/**
 * 验证身份 gitee
 */
function checkAuthGitee(req, appToken) {
  //gitee的验证方式
  return appToken == req.headers["x-gitee-token"];
}

function getCheckAuthFunc(type) {
  return type === "gitee" ? checkAuthGitee : checkAuthGithub;
}

/**
 * 验证IP，只对内部的gitlab有效
 * @param {*} req
 */
function checkIp(req) {
  let flag = whiteListIps.includes(req.ip);
  flag ? console.log("ip验证通过") : console.log("ip验证失败");
  console.log("源IP：", req.ip);
  console.log("白名单：", whiteListIps);
  return flag;
}

module.exports = {
  getCheckAuthFunc,
  checkIp,
};
